package controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Calendar;
import view.MainWindow;
import model.*;

public class FeedController {

	public void createFeed(String id_client, int discounter) {

		Feed newFeed = new Feed();

		int repeatFeed = Integer.parseInt(MainWindow.getTextField_7());
		if (repeatFeed > 0)
			newFeed.numberRepeat = repeatFeed;
		else
			newFeed.numberRepeat = 1;

		newFeed.text = MainWindow.getTextArea();
		newFeed.numberSimbols = newFeed.text.length();
		MainWindow.setTxtId(Integer.toString(newFeed.numberSimbols));

		int dubl = Integer.parseInt(MainWindow.getTextField_5());
		if (dubl > 0)
			newFeed.numberDublication = dubl;
		else
			newFeed.numberDublication = 1;

		int cell = newFeed.numberSimbols / 140;
		if (Integer.parseInt(MainWindow.getTextField_6()) > cell)
			newFeed.numberCell = Integer.parseInt(MainWindow.getTextField_6());
		else
			newFeed.numberCell = cell;

		newFeed.calculateCost(Integer.parseInt(MainWindow.getTextField_8()), discounter);
		newFeed.activ = 1;
		MainWindow.setTxtId(Integer.toString(newFeed.numberSimbols));
		MainWindow.setTextField_4(Integer.toString(newFeed.cost));
		MainWindow.setTextField_6(Integer.toString(newFeed.numberCell));

		try {

			String curTime = new java.text.SimpleDateFormat("yyyy-MM-dd")
					.format(Calendar.getInstance().getTime());

			Connection conn = DatabaseConnection.getInstance().getConnection();
			PreparedStatement ps = conn
					.prepareStatement(String
							.format("INSERT INTO feed VALUES (NULL, %s, %s, %s, %s, %s, \"%s\", \"%s\", %s, \"%s\")",
									id_client,
									Integer.toString(newFeed.numberSimbols),
									Integer.toString(newFeed.numberRepeat),
									Integer.toString(newFeed.numberDublication),
									Integer.toString(newFeed.cost),
									newFeed.text, curTime,
									Integer.toString(newFeed.numberCell),
									Integer.toString(newFeed.activ)));
			ps.executeUpdate();
			ps = conn.prepareStatement(String.format("UPDATE clients SET pay_sum=pay_sum+%s WHERE id_client=%s", newFeed.cost, id_client));
			ps.executeUpdate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
